#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import optparse
import os
import logging
import string
import sys
import tempfile

from oriolus.trotter.core import Downloader, DownloadError, Indexer, Fetcher
from oriolus.trotter.fetchers.wgetfetcher import WgetFetcher
from oriolus.trotter.fetchers.persistentfetcher import PersistentFetcher
from oriolus.trotter.fetchers.emptyfetcher import EmptyFetcher

def update(indexer, args):
    if (args in [None, (), []]):
        indexer.update()
    else:
        urls = string.join(args, ",")
        indexer.update(urls)

def addurls(indexer, args):
    if (args in [None, (), []]):
        sys.stdout.write("parameter addurls must be contain source urls.")
    else:
        urls = string.join(args, ",")
        indexer.add_urls(urls)
        
def getversions(indexer, args):
    version_list = indexer.get_versions(args[0])
    if version_list in [None, (), []]:
        sys.stdout.write("Packet not available.")
    else:
        versions = string.join(version_list, "\n")
        sys.stdout.write(versions)

def list(indexer):
    packet_list = indexer.get_packet_list()
    if packet_list in [None, (), []]:
        sys.stdout.write("Not packets available.")
    else:
        packets = string.join(packet_list, "\n")
        sys.stdout.write(packets)
    
    
def download(indexer, args):
    try:
        if len(args) > 1:
            sys.stdout.write(indexer.download(args[0], args[1]))
        else:
            sys.stdout.write(indexer.download(args[0]))
    except DownloadError, ex:
        sys.stdout.write(ex.message)

def run():
    usage = "usage: %prog [options] command [arguments]\nCommands:\n  addurls (add) [url[, url]] - add urls to local source list\n  update (up) [url[, url]] - update local packet list\n  list (ls) - get packet list\n  getversions (gv) packetname - get packet versions\n  download (dl) packetname [version] - download packet"
    parser = optparse.OptionParser(version = "Oriolus Trotter 1.0", usage = usage)
    
    parser.add_option("-f", "--fetcher", dest = "fetcher", type="choice", choices=["wget", "builtin"], default = "builtin", help = "set fetcher, which will be used for getting packet [default: %default]")
    parser.add_option("-t", "--timeout", dest = "timeout", type = "int", default = 30, help = "network timeout [default: %default]")
    parser.add_option("-u", "--userconfig", dest = "filename", help = "input file for configuring trotter [not available now]")
    parser.add_option("-l", dest = "loglevel", action="count", help = "set logging level, the count of option defines logging level (-l: DEBUG, -ll: INFO, -lll: WARNING, -llll: ERROR, -lllll: CRITICAL)")
    parser.add_option("-v", "--no-verification", dest = "no_verification", action = "store_false", default = True, help = "disable packet verification [default: %default]")
    parser.add_option("-k", "--keyring", dest = "keyring", help = "input file path for GPG keyring")
    parser.add_option("--log", dest = "logfilename", default = "./trotter.log.txt", help = "set log file name [default: %default]")
    parser.add_option("-n", "--user-name", dest = "login", help = "set user name for access to repository")
    parser.add_option("-p", "--password", dest = "password", help = "set password for access to repository")

    (options, args) = parser.parse_args()
    
    if len(args) > 0:
        cache = os.path.abspath(tempfile.mkdtemp())
        workdir = os.path.expanduser("~/.trotter")
        if not os.path.exists(workdir):
            os.makedirs(workdir)

        if options.fetcher == "wget":
            fetcher = WgetFetcher
        elif options.fetcher == "builtin":
            fetcher = PersistentFetcher
        else:
            parser.print_help()

        loglevel = 0
        if options.loglevel:
            if options.loglevel > 5:
                options.loglevel = 5
            loglevel = options.loglevel * 10
            logging.basicConfig(level = loglevel, filename = options.logfilename, format = "%(asctime)-15s [%(thread)d] %(levelname)-5s %(name)s - %(message)s", )
        else:
            logging.basicConfig(level = logging.INFO, format = "[%(levelname)s] %(message)s", )

        if options.keyring:
            keyring = options.keyring
        else:
            keyring = None
            
        login = None
        if options.login:
            login = options.login
            
        password = None
        if options.password:
            password = options.password
            
        cmd = args[0]
        if cmd == "up" or cmd == "update" or cmd == "dl" or cmd == "download":
            indexer = Indexer(cache, workdir, fetcher, options.timeout, options.no_verification, keyring, login, password)
        else:
            indexer = Indexer(cache, workdir, EmptyFetcher, options.timeout, options.no_verification, keyring)
            
        if cmd == "up" or cmd == "update":
            update(indexer, args[1:])
        elif cmd == "gv" or cmd == "getversions":
            getversions(indexer, args[1:])
        elif cmd == "ls" or cmd == "list":
            list(indexer)
        elif cmd == "dl" or cmd == "download":
            download(indexer, args[1:])
        elif cmd == "add" or cmd == "addurls":
            addurls(indexer, args[1:])
        else:
            parser.print_help()
        
    else:
        parser.print_help()

if __name__ == "__main__":
    run()
